import React from "react";
import { Table, Button, Tag, Popconfirm, message, Spin } from "antd";
import { useEffect, useState, useRef } from "react";
import api from "@/api/blog/share";
import Edit from "./component/edit";
import { getOptNameType } from "@/utils/dict";
import { getRole } from "@/utils/localStorage"
import { RoleButton, RoleLink } from "@/components/RoleButton"
export default function Index() {
    const [dt, setdt] = useState([]);
    const [loading, setLoading] = useState(false);
    const editEl = useRef();
    const openEdit = (_id, type) => {
        editEl.current.open(_id, type);
    };
    useEffect(() => {
        getlist();
    }, []);
    const remove = async (_id) => {
        const res = await api.remove({ _id });
        await getlist();
        message.success(res.msg);
    };
    const getlist = async () => {
        setLoading(true);
        api.getlist()
            .then((res) => {
                setdt(res.data);
                setLoading(false);
            })
            .catch(() => {
                setLoading(false);
            });
    };
    const openPage = (url) => {
        window.open(url)
    }
    const columns = [
        {
            title: "标题",
            dataIndex: "title",
            key: "title",
        },
        {
            title: "标签",
            dataIndex: "tag",
            key: "tag",
            render: (_) => <Tag> {getOptNameType("share_type", _)} </Tag>,
        },
        {
            title: "备注",
            dataIndex: "desc",
            key: "desc",
        },
        {
            title: "创建时间",
            dataIndex: "createTime",
            key: "createTime",
        },
        {
            title: "操作",
            width: "120px",
            render: (_, record) => (
                <div style={{ display: "flex" }}>
                    <Button type="link" onClick={() => { openPage(record.targetUrl) }}> 查 看 </Button>

                    <RoleLink role={getRole()} onClick={() => { openEdit(record._id, "update") }}> 编 辑 </RoleLink>

                    <Popconfirm title="您确认要删除吗？" onConfirm={() => { remove(record._id) }} okText="Yes" cancelText="No">
                        <RoleLink role={getRole()} danger>  删 除 </RoleLink>
                    </Popconfirm>

                </div>
            ),
        },
    ];
    return (
        <>
            <RoleButton
                role={getRole()}
                type="primary"
                style={{ marginBottom: 10 }}
                onClick={() => {
                    openEdit(-1, "add");
                }}>
                新增分享
            </RoleButton>
            <Spin spinning={loading}>
                <Table dataSource={dt} rowKey="_id" columns={columns} />
            </Spin>
            <Edit callback={getlist} ref={editEl} />
        </>
    );
}
